<template>
  <div class="attendance-container">
    <el-card>
      <div class="header-title">工时记录申请</div>
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px" style="max-width: 500px; margin: 0 auto;">
        <el-form-item label="岗位名称" prop="positionId">
          <el-select v-model="form.positionId" placeholder="请选择岗位" filterable>
            <el-option v-for="item in positions" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker 
            v-model="form.startTime" 
            type="datetime" 
            placeholder="选择开始时间" 
            format="YYYY-MM-DD HH:mm" 
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker 
            v-model="form.endTime" 
            type="datetime" 
            placeholder="选择结束时间" 
            format="YYYY-MM-DD HH:mm" 
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="工作描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入工作内容" />
        </el-form-item>
        <el-form-item label="证明图片" prop="file">
          <div class="upload-container">
            <el-upload
              class="image-uploader"
              action=""
              :auto-upload="false"
              :show-file-list="false"
              :on-change="handleFileChange"
              :before-upload="beforeUpload"
              accept=".jpg,.jpeg"
            >
              <div v-if="!imageUrl" class="upload-placeholder">
                <el-icon class="upload-icon"><Plus /></el-icon>
                <div class="upload-text">点击上传图片</div>
                <div class="upload-tip">仅支持jpg格式</div>
              </div>
              <img v-else :src="imageUrl" class="uploaded-image" />
            </el-upload>
            <div v-if="imageUrl" class="image-actions">
              <el-button type="danger" size="small" @click="removeImage">删除图片</el-button>
            </div>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm" :loading="loading">提交</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';
import axios from 'axios';

const positions = ref([]);
const formRef = ref(null);
const loading = ref(false);
const imageUrl = ref('');

const form = reactive({
  positionId: '',
  startTime: '',
  endTime: '',
  description: '',
  file: null
});

const rules = {
  positionId: [{ required: true, message: '请选择岗位', trigger: 'change' }],
  startTime: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
  endTime: [{ required: true, message: '请选择结束时间', trigger: 'change' }],
  description: [{ required: true, message: '请输入工作内容', trigger: 'blur' }],
  file: [{ required: true, message: '请上传jpg图片', trigger: 'change' }]
};

const handleFileChange = (file) => {
  form.file = file.raw;
  // 创建本地预览URL
  imageUrl.value = URL.createObjectURL(file.raw);
};

const beforeUpload = (file) => {
  const isJpg = file.type === 'image/jpeg';
  if (!isJpg) {
    ElMessage.error('只能上传jpg格式图片');
    return false;
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过2MB');
    return false;
  }
  return true;
};

const removeImage = () => {
  form.file = null;
  imageUrl.value = '';
  if (formRef.value) {
    formRef.value.clearValidate('file');
  }
};

const fetchPositions = async () => {
  try {
    const token = localStorage.getItem('token');
    const res = await axios.get('/api/student/work-time-positions', {
      headers: { Authorization: `Bearer ${token}` }
    });
    if (res.data.code === 0) {
      positions.value = res.data.data;
    } else {
      ElMessage.error(res.data.msg || '获取岗位失败');
    }
  } catch (e) {
    ElMessage.error('获取岗位失败: ' + e.message);
  }
};

const submitForm = async () => {
  if (!formRef.value) return;
  await formRef.value.validate();
  loading.value = true;
  try {
    const token = localStorage.getItem('token');
    const formData = new FormData();
    formData.append('positionId', form.positionId);
    formData.append('startTime', form.startTime);
    formData.append('endTime', form.endTime);
    formData.append('description', form.description);
    formData.append('file', form.file);
    const res = await axios.post('/api/student/work-time-record', formData, {
      headers: {
        Authorization: `Bearer ${token}`,
        'Content-Type': 'multipart/form-data'
      }
    });
    if (res.data.code === 0) {
      ElMessage.success('提交成功');
      form.positionId = '';
      form.startTime = '';
      form.endTime = '';
      form.description = '';
      form.file = null;
      imageUrl.value = '';
      formRef.value.resetFields();
    } else {
      ElMessage.error(res.data.msg || '提交失败');
    }
  } catch (e) {
    ElMessage.error('提交失败: ' + e.message);
  } finally {
    loading.value = false;
  }
};

onMounted(() => {
  fetchPositions();
});
</script>

<style scoped>
.attendance-container {
  padding: 24px;
}

.header-title {
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 10px;
  color: #222;
  text-align: center;
}

.upload-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10px;
}

.image-uploader {
  border: 2px dashed #d9d9d9;
  border-radius: 8px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: border-color 0.3s;
}

.image-uploader:hover {
  border-color: #409eff;
}

.upload-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 20px;
  text-align: center;
}

.upload-icon {
  font-size: 48px;
  color: #c0c4cc;
  margin-bottom: 10px;
}

.upload-text {
  font-size: 16px;
  color: #606266;
  margin-bottom: 5px;
}

.upload-tip {
  font-size: 12px;
  color: #c0c4cc;
}

.uploaded-image {
  width: 200px;
  height: 150px;
  object-fit: cover;
  border-radius: 6px;
}

.image-actions {
  display: flex;
  gap: 10px;
}
</style> 